package com.example.application4.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

import com.example.application4.R;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class AddDiaryActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView createDateTextView;
    private EditText titleInput, contentInput;
    private Button createButton, returnButton;
    private static final String DATE_PATTERN = "yyyy-MM-dd";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.diary_add);

        // 初始化视图
        createDateTextView = findViewById(R.id.createDate);
        titleInput = findViewById(R.id.title_input);
        contentInput = findViewById(R.id.content_input);
        createButton = findViewById(R.id.create_button);
        returnButton = findViewById(R.id.return_button);

        // 设置创建日期
        setDate();

        // 设置按钮点击事件
        createButton.setOnClickListener(this);
        returnButton.setOnClickListener(this);
    }

    // 设置创建日期
    private void setDate() {
        LocalDate currentDate = LocalDate.now();
        String date = currentDate.format(DateTimeFormatter.ofPattern(DATE_PATTERN)); // 格式化日期
        createDateTextView.setText(date);
    }

    @Override
    public void onClick(View view) {
        try {
            if (view.getId() == R.id.create_button) {
                handleCreateButtonClick();
            } else if (view.getId() == R.id.return_button) {
                finish();
            }
        } catch (Exception e) {
            Toast.makeText(this, "发生意外错误，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleCreateButtonClick() {
        String title = titleInput.getText().toString().trim();
        String content = contentInput.getText().toString().trim();
        String date = createDateTextView.getText().toString();

        if (title.isEmpty()) {
            titleInput.setError("标题不能为空");
        } else if (content.isEmpty()) {
            contentInput.setError("内容不能为空");
        } else {
            // 保存数据
            setData(title, content, date); // 调用 setData 方法保存数据
            Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            finish(); // 结束当前 Activity
        }
    }

    private void setData(String title, String content, String date) {
        // TODO: 保存到数据库或SharedPreferences

        Intent intent = new Intent();
        intent.putExtra("title", title);
        intent.putExtra("content", content);
        intent.putExtra("date", date);
        setResult(RESULT_OK, intent); // 返回 RESULT_OK 附带数据
    }
}